package com.neusoft.neuiotms.common.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.common.model.Dictionary;
import com.neusoft.neuiotms.common.model.QDictionary;
import com.neusoft.neuiotms.common.repository.CustomizedDictionaryRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedDictionaryRepositoryImpl extends AbstractRepository implements CustomizedDictionaryRepository {

    @Override
    public List<Dictionary> findAll(final Searchable searchable) {
        final QDictionary qDictionary = QDictionary.dictionary;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Dictionary> query = this.query().selectFrom(qDictionary);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<Dictionary> search(final Pageable pageable, final Searchable searchable) {
        final QDictionary qDictionary = QDictionary.dictionary;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Dictionary> query = this.query().selectFrom(qDictionary);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return Dictionary.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QDictionary qDictionary = QDictionary.dictionary;

        if (!StringUtils.isEmpty(searchable.getStrValue("code"))) {
            where.and(super.containsStr(qDictionary.code, searchable, "code"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("text"))) {
            where.and(super.containsStr(qDictionary.text, searchable, "text"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("type"))) {
            where.and(super.containsStr(qDictionary.dictionaryType.type, searchable, "type"));
        }

        return where;
    }
}
